﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Yuchen.NPA.Core.CompilerService.RegularExpression
{
    [Serializable]
    public class State
    {
        private static int id = 0;
        public string Id { get; }

        public bool IsAccepted { get; set; }
        public bool IsStart { get; set; }
        public bool IsError { get; set; }
        public State()
        {
            Id = "#" + (id++);
            NextStates = new Dictionary<Edge, State>();
        }

        public List<State> States => GetStates(new List<State>(), this).Distinct().ToList();

        private static List<State> GetStates(List<State> states, State state)
        {
            if (states.Contains(state))
            {
                return states;
            }
            states.Add(state);
            foreach (var nextStatesValue in state.NextStates.Values)
            {
                GetStates(states, nextStatesValue);
            }

            return states;
        }

        public Dictionary<Edge, State> NextStates { get; set; }

        public override string ToString()
        {
            return string.Join(",",
                NextStates.Select(x => $"{Id} -- {x.Key.InputCharacter ?? 'ｅ'} -->{x.Value.Id}"));
        }

        public State AddEdges(Edge edge, State state)
        {
            NextStates.Add(edge, state);
            return state;
        }

        public State AddNextState()
        {
            var state = new State();
            AddNextState(state);
            return state;
        }

        public State AddNextState(State state)
        {
            AddEdges(new Edge(null), state);
            return state;
        }

        public State AddNextState(char? c)
        {
            var state = new State();
            AddNextState(c, state);
            return state;
        }

        public State AddNextState(char? c, State state)
        {
            AddEdges(new Edge(c), state);
            return state;
        }
    }
}
